package com.mo.lib.utils.view

import android.text.InputFilter
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.widget.EditText
import com.mo.lib.utils.showToast

/**
 * @ author：mo
 * @ data：2021/9/14:17:02
 * @ 功能：EditText扩展类
 */


/** 获取输入框密码样式状态   true==密码模式 、false==正常模式*/
fun EditText.pwType() = this.transformationMethod is PasswordTransformationMethod

/** 切换输入框密码模式,返回是否已设置为正常模式，true==正常模式、false==密码模式  */
fun EditText.pwTypeChange(): Boolean { //默认正常显示
    val isPw = this.transformationMethod is HideReturnsTransformationMethod
    this.transformationMethod = if (isPw) {
        PasswordTransformationMethod()
    } else HideReturnsTransformationMethod()
    return !isPw
}

/** 设置输入框是否为密码模式*/
fun EditText.pwType(isPw: Boolean) {
    this.transformationMethod = if (isPw) {
        PasswordTransformationMethod()
    } else HideReturnsTransformationMethod()
}

/** 设置过滤表情*/
fun EditText.setProhibitEmoji() {
    this.filters = arrayOf(InputFilters().getInputFilterProhibitEmoji())
}

/** 光标移动至所显示文字的末尾*/
fun EditText.setCursorToLast() {
    this.setSelection(this.text.length)
}

/** s输入过滤器*/
class InputFilters {
    /** 表情过滤器*/
    fun getInputFilterProhibitEmoji(): InputFilter {
        return InputFilter { source, start, end, dest, dstart, dend ->
            val buffer = StringBuffer()
            var i = start
            while (i < end) {
                val codePoint = source[i]
                if (!getIsEmoji(codePoint)) {
                    buffer.append(codePoint)
                } else {
                    showToast("不能含有第三方表情")
                    i++
                    i++
                    continue
                }
                i++
            }
            if (source is Spanned) {
                val sp = SpannableString(buffer)
                TextUtils.copySpansFrom(source, start, end, null, sp, 0)
                sp
            } else {
                buffer
            }
        }
    }

    /** 是否包含表情*/
    fun getIsEmoji(codePoint: Char): Boolean {
        return if (codePoint.toInt() == 0x0 || codePoint.toInt() == 0x9 || codePoint.toInt() == 0xA || codePoint.toInt() == 0xD || codePoint.toInt() >= 0x20 && codePoint.toInt() <= 0xD7FF || codePoint.toInt() >= 0xE000 && codePoint.toInt() <= 0xFFFD || codePoint.toInt() >= 0x10000 && codePoint.toInt() <= 0x10FFFF) false else true
    }
}



